import { getEntireRoomList } from '@/services/modules/entire'
import * as actionTypes from './constants'

export const changeCurrentPageAction = (currentPage) => {
  return {
    type: actionTypes.CHANGE_CURRENT_PAGE,
    currentPage,
  }
}

export const changeRoomListAction = (roomList) => {
  return {
    type: actionTypes.CHANGE_ROOM_LIST,
    roomList,
  }
}

export const changeTotalCountAction = (totalCount) => {
  return {
    type: actionTypes.CHANGE_TOTAL_COUNT,
    totalCount,
  }
}

export const changeIsLoadingAction = (isLoading) => {
  return {
    type: actionTypes.CHANGE_IS_LOADING,
    isLoading,
  }
}

export const fetchRoomListAction = (page = 0) => {
  return async (dispatch, getState) => {
    // 修改 currentPage
    dispatch(changeCurrentPageAction(page))

    // 开启蒙版
    dispatch(changeIsLoadingAction(true))
    // 获取当前页码
    // const currentPage = getState().entire.currentPage
    // 根据页码获取最新的数据
    // 服务器接收的参数是偏移量,所以是当前页码 * 每页条目数 20
    const res = await getEntireRoomList(page * 20)
    const roomList = res.list
    const totalCount = res.totalCount
    // 保存到 store 中
    dispatch(changeRoomListAction(roomList))
    dispatch(changeTotalCountAction(totalCount))
    // 关闭蒙版
    dispatch(changeIsLoadingAction(false))
  }
}
